<?php

namespace Infrastructure;

class Router {
        
    protected $_request = [];
    
    public function __construct($requestPath) {
        
        $controller = $action = '';
        $parts = preg_split('#/#', trim($requestPath, '/'));
        
        if (count($parts) === 2) {
            list($controller, $action) = $parts;
        } elseif (count($parts) === 1) {
            $controller = $parts[0];    
        }
        
        $this->_request['controller'] = !$controller ? 'index' : $controller;
        $this->_request['action']     = !$action     ? 'index' : $action;
    }
    
    public function route() {
        
        $controller = $this->_request['controller'] . 'Controller';
        $classController = '\Controllers\\' . $controller;
        
        if (!class_exists($classController)) {
            http_response_code(404);
            exit;
        }
        
        $controllerInstance = new $classController(
            $this->_request['controller'], 
            new ViewBuilder($this->_request),
            new SimpleDependencyInjector()
        );
        
        $method = filter_input(INPUT_SERVER, 'REQUEST_METHOD');
        $action = $this->_request['action'] . 'Action' . $method;
        if (!method_exists($controllerInstance, $action)) {
            http_response_code(404);
            exit;
        }
        
        $controllerInstance->{$action}();
    }
}

